// 弃用（递归时，主树枝长到最大高度前，分树枝会不断重置，不能长高，角度一直变。主树枝长到最大高度后，分树枝才会确定角度并长高）
import React, {Component} from "react";

export default function withData(WrappedComponent, data) {
  return class extends Component {
    constructor (props) {
      super(props)
      this.el = React.createRef()
      this.static = {
        level: props.level ? props.level + 1 : 1,
        // 树干最大宽度
        maxWidth: (props.maxWidth ?? data.maxWidth) / 2,
        isRoot: false,
        className: props.className,
      }
      this.state = {
        // 树干初始长度
        height: props.height ?? data.height ?? 1,
      }
      this.className = props.className ?? ''
      // 生长系数
      this.growIndex = Math.random()
      // 是否长分支
      this.isSplit = false
      // 每次分裂的数量
      this.splitNum = Number.parseInt(3 * Math.random())
      this.child = new Array(1).fill([30, this.getRotate(false)])
      // 分裂时的高度
      this.splitHeight = 1.7
      // 分裂次数
      this.k = 1
      // 检查是否停止生长字段
      this.maxHeight = 0
      let {isRoot} = props
      this.rotate = this.getRotate(isRoot)
    }
    componentDidMount () {
      this.timer = setInterval(this.trunkGrow, data.growTimes)
    }
    componentWillUnmount () {
      clearInterval(this.timer)
    }

    getRotate = (isRoot) => {
      // 生长角度
      let rootIndex = data.rootIndex ?? 20
      let notRootIndex = data.notRootIndex ?? 180
      return Math.random() * (isRoot ? rootIndex : notRootIndex)
    }
    
    // 树干生长
    trunkGrow = () => {
      if (this.isStopGrowing() || this.static.level === 4) {
        clearInterval(this.timer)
        return
      }
      let {isRoot} = this.props
      this.setState({height: this.state.height + this.growIndex})
      // console.log('树干长大了!!!!!')
      let trunkBottom = this.state.height * 50 / (2+Math.random())
      if (isRoot) {
        if (this.state.height > this.k * this.splitHeight) {
          // this.splitNum = Number.parseInt(3 * Math.random())
          // // 50是系数，1/2到1/3处分支
          // this.child.push(...new Array(this.splitNum).fill([trunkBottom, this.getRotate(isRoot)]))
          this.isSplit = true
          // this.k++
        }
      } else if (!this.isSplit && this.state.height > this.splitHeight) {
        this.child.push(...new Array(this.splitNum).fill([trunkBottom, this.getRotate(isRoot)]))
        this.isSplit = true
      }
      console.log(this.el.current, this.child.map(item => ({height: item[0], rotate: item[1]})))
    }
    // 检查是否停止生长
    isStopGrowing = () => {
      let clinetHeight = Number(getComputedStyle(this.el.current).height.split('px')[0])
      if (clinetHeight > this.maxHeight) {
        this.maxHeight = clinetHeight
        return false
      } else {
        return true
      }
    }
    // 点击可以修剪
    cut = (event) => {
      event.stopPropagation()
      this.el.current.parentElement.removeChild(this.el.current)
      this.static.level--
      // event.target.parentElement.removeChild(event.target)
    }
    render() {
      const newProps = Object.assign({}, this.props, {
        cut: this.cut,
        el: this.el,
        rotate: this.rotate,
        growTimes: data.growTimes,
        ...this.state
      })
      if (!newProps.maxWidth) newProps.maxWidth = 60
      const newStatic = Object.assign({}, this.static, {
        // height: data.height,
        growTimes: data.growTimes,
      })
      const Self = withData(WrappedComponent, data)
      return (
        <WrappedComponent {...newProps}>
          {this.props.children}
          {
            this.isSplit && this.child.map((item, index) => {
              return (
                <Self key={index} {...newStatic} trunkBottom={item[0]} rotate={item[1]}>
                  {this.props.children}
                </Self>
              )
            })
          }
        </WrappedComponent>
      )
    }
  }
}